import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../shared/widgets/fancy_header.dart';
import '../../../shared/widgets/aurora_background.dart';
import '../../../shared/widgets/glass_card.dart';
import '../../../shared/widgets/starfield.dart';
import '../../../shared/widgets/stickers_float.dart';
import '../../../core/api/api_service.dart';
import '../../../core/providers/user_extra_info_provider.dart';

class DashboardPage extends ConsumerStatefulWidget {
  const DashboardPage({super.key});

  @override
  ConsumerState<DashboardPage> createState() => _DashboardPageState();
}

class _DashboardPageState extends ConsumerState<DashboardPage> {
  @override
  void initState() {
    super.initState();
    _loadUserExtraInfo();
  }

  Future<void> _loadUserExtraInfo() async {
    try {
      // 先检查本地是否已有数据
      final userExtraInfoNotifier = ref.read(userExtraInfoProvider.notifier);
      if (!userExtraInfoNotifier.needsServerSync) {
        print('📱 本地已有完整的用户额外信息，跳过API请求');
        print('📊 数据状态: ${userExtraInfoNotifier.dataStatus}');
        return;
      }

      print('🔄 开始获取用户额外信息...');
      final response = await ApiService().getUserExtraInfo();
      print('✅ 获取用户额外信息成功: ${response.data}');

      // 解析响应数据并更新状态
      if (response.data != null && response.data['data'] != null) {
        await userExtraInfoNotifier.updateFromApiResponse(
          response.data['data'],
        );
      }
    } catch (e) {
      print('❌ 获取用户额外信息失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () async {
        // 用户主动刷新时，强制重新获取用户信息
        print('🔄 用户主动刷新，强制获取最新用户信息...');
        await _forceRefreshUserExtraInfo();
        await Future.delayed(const Duration(seconds: 1));
      },
      child: Stack(
        children: <Widget>[
          const AuroraBackground(),
          const Starfield(starCount: 80),
          const StickersFloat(),
          ListView(
            padding: const EdgeInsets.all(12.0),
            children: <Widget>[
              const FancyHeader(
                title: '欢迎回来，今天也要元气满满！',
                subtitle: '先从一个小目标开始吧～',
                icon: Icons.rocket_launch,
                height: 130,
              ),
              const SizedBox(height: 12),
              GlassCard(child: _buildUserInfoCard()),
              const SizedBox(height: 12),
              GlassCard(child: _buildTodayOverview()),
              const SizedBox(height: 12),
              GlassCard(child: _buildLearningStats()),
              const SizedBox(height: 12),
              GlassCard(child: _buildQuickActions()),
              const SizedBox(height: 12),
              GlassCard(child: _buildTaskList()),
            ],
          ),
        ],
      ),
    );
  }

  // 原顶部欢迎横幅已被 FancyHeader 替代

  Widget _buildUserInfoCard() {
    return Consumer(
      builder: (context, ref, child) {
        final userExtraInfo = ref.watch(userExtraInfoProvider);
        final ColorScheme cs = Theme.of(context).colorScheme;

        return Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: cs.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Row(
            children: <Widget>[
              CircleAvatar(
                radius: 20,
                backgroundColor: cs.primary,
                child: const Icon(Icons.person, color: Colors.white, size: 20),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '学生用户',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      userExtraInfo?.fullGradeInfo ?? '未设置年级',
                      style: Theme.of(
                        context,
                      ).textTheme.bodySmall?.copyWith(color: Colors.grey),
                    ),
                    if (userExtraInfo != null) ...[
                      const SizedBox(height: 2),
                      Text(
                        '科目: ${userExtraInfo.subjectsList.join('、')}',
                        style: Theme.of(
                          context,
                        ).textTheme.labelSmall?.copyWith(color: Colors.grey),
                      ),
                    ],
                  ],
                ),
              ),
              Icon(
                Icons.notifications_outlined,
                color: cs.onSurface.withOpacity(0.6),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTodayOverview() {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: cs.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '今日学习概览',
                style: Theme.of(
                  context,
                ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              Row(
                children: <Widget>[
                  Expanded(child: _buildStatItem('待完成任务', '3', Icons.task_alt)),
                  Expanded(
                    child: _buildStatItem('建议学习时长', '45分钟', Icons.timer),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: cs.surface,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: <Widget>[
              Icon(icon, color: cs.primary, size: 18),
              const SizedBox(height: 3),
              Text(
                value,
                style: Theme.of(
                  context,
                ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 2),
              Text(
                label,
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: cs.onSurface.withOpacity(0.6),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildLearningStats() {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: cs.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '学习数据',
                style: Theme.of(
                  context,
                ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              Row(
                children: <Widget>[
                  Expanded(
                    child: _buildStatItem(
                      '连续学习',
                      '7天',
                      Icons.local_fire_department,
                    ),
                  ),
                  Expanded(
                    child: _buildStatItem('掌握知识点', '12个', Icons.psychology),
                  ),
                  Expanded(
                    child: _buildStatItem('完成题目', '156道', Icons.check_circle),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildQuickActions() {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: cs.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '快捷功能',
                style: Theme.of(
                  context,
                ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              Wrap(
                spacing: 12,
                runSpacing: 12,
                children: <Widget>[
                  _QuickCard(
                    title: 'AI助手',
                    icon: Icons.smart_toy_outlined,
                    onTap: () => context.go('/capture'),
                  ),
                  _QuickCard(
                    title: 'AI讲解',
                    icon: Icons.menu_book_outlined,
                    onTap: () => context.go('/explain'),
                  ),
                  _QuickCard(
                    title: '教材大纲',
                    icon: Icons.book_outlined,
                    onTap: () => context.go('/curriculum'),
                  ),
                  _QuickCard(
                    title: '错题本',
                    icon: Icons.bookmark_border,
                    onTap: () => context.go('/mistakes'),
                  ),
                  _QuickCard(
                    title: '学习计划',
                    icon: Icons.calendar_today_outlined,
                    onTap: () {},
                  ),
                  _QuickCard(
                    title: '趣味学习',
                    icon: Icons.web_outlined,
                    onTap: () => context.go('/h5'),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTaskList() {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: cs.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '今日任务',
                style: Theme.of(
                  context,
                ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              _buildTaskItem('数学练习 - 一元一次方程', '30分钟', false),
              _buildTaskItem('英语单词复习', '15分钟', false),
              _buildTaskItem('错题复习', '20分钟', true),
            ],
          ),
        );
      },
    );
  }

  Widget _buildTaskItem(String title, String duration, bool isCompleted) {
    return Builder(
      builder: (context) {
        final ColorScheme cs = Theme.of(context).colorScheme;
        return Container(
          margin: const EdgeInsets.only(bottom: 6),
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: cs.surface,
            borderRadius: BorderRadius.circular(8),
            border:
                isCompleted
                    ? Border.all(color: Colors.green.withOpacity(0.3))
                    : null,
          ),
          child: Row(
            children: <Widget>[
              Icon(
                isCompleted ? Icons.check_circle : Icons.radio_button_unchecked,
                color:
                    isCompleted ? Colors.green : cs.onSurface.withOpacity(0.6),
                size: 18,
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      title,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        fontWeight: FontWeight.w500,
                        decoration:
                            isCompleted ? TextDecoration.lineThrough : null,
                        color:
                            isCompleted
                                ? cs.onSurface.withOpacity(0.6)
                                : cs.onSurface,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      duration,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: cs.onSurface.withOpacity(0.6),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _forceRefreshUserExtraInfo() async {
    try {
      print('🔄 强制刷新用户额外信息...');
      final response = await ApiService().getUserExtraInfo();
      print('✅ 强制刷新成功: ${response.data}');

      // 解析响应数据并更新状态
      if (response.data != null && response.data['data'] != null) {
        final userExtraInfoNotifier = ref.read(userExtraInfoProvider.notifier);
        await userExtraInfoNotifier.updateFromApiResponse(
          response.data['data'],
        );
      }
    } catch (e) {
      print('❌ 强制刷新失败: $e');
    }
  }
}

class _QuickCard extends StatefulWidget {
  const _QuickCard({
    required this.title,
    required this.icon,
    required this.onTap,
  });
  final String title;
  final IconData icon;
  final VoidCallback onTap;

  @override
  State<_QuickCard> createState() => _QuickCardState();
}

class _QuickCardState extends State<_QuickCard> {
  double _scale = 1.0;

  void _press(bool down) {
    setState(() => _scale = down ? 0.97 : 1.0);
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return GestureDetector(
      onTapDown: (_) => _press(true),
      onTapCancel: () => _press(false),
      onTapUp: (_) {
        _press(false);
        widget.onTap();
      },
      child: AnimatedScale(
        duration: const Duration(milliseconds: 110),
        scale: _scale,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          width: 120,
          height: 72,
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            color: theme.colorScheme.surface,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.04),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 28,
                height: 28,
                decoration: BoxDecoration(
                  color: theme.colorScheme.primaryContainer.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  widget.icon,
                  color: theme.colorScheme.primary,
                  size: 16,
                ),
              ),
              const Spacer(),
              Text(
                widget.title,
                style: Theme.of(
                  context,
                ).textTheme.labelMedium?.copyWith(fontWeight: FontWeight.w700),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
